/*
 * Principal.java
 *
 * Created on 10/03/2009, 17:41:24
 */

package t1;

/**
 * @author Ferreyra Montes, Emmanuel Alan
 * @legajo 49271
 * @curso 4K6 - Turno Mañana
 */

import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author emmanuel
 */
public class Principal extends javax.swing.JFrame {

    /** Creates new form Principal */
    public Principal() {
        initComponents();
        limpiar();
        txtBuscar.setToolTipText("Aquí puedes ingresar el directorio por teclado o buscarlo con el botón \"...\"");
        btnBorrarBak.setToolTipText("Borrar los archivos con extensión .bak del directorio elegido");
        btnMoverA.setToolTipText("Mueve solo los archivos del directorio seleccionado");
        btnEliminarDir.setToolTipText("Borrar el directorio seleccionado y su contenido");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        txtBuscar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        area = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        txtTipoArchivo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtTamanio = new javax.swing.JTextField();
        btnBorrarBak = new javax.swing.JButton();
        btnMoverA = new javax.swing.JButton();
        btnEliminarDir = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();

        setTitle("Tarea 1");
        setDefaultCloseOperation(3);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));

        jButton1.setLabel("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        txtBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtBuscarActionPerformed(evt);
            }
        });

        area.setColumns(20);
        area.setEditable(false);
        area.setRows(5);
        jScrollPane1.setViewportView(area);

        jLabel1.setText("Tipo de archivo:");

        txtTipoArchivo.setEditable(false);

        jLabel2.setText("Tamaño:");

        txtTamanio.setEditable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(txtBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTipoArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTamanio, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTipoArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTamanio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24))
        );

        btnBorrarBak.setText("Borrar .bak");
        btnBorrarBak.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarBakActionPerformed(evt);
            }
        });

        btnMoverA.setText("Mover archivos a...");
        btnMoverA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMoverAActionPerformed(evt);
            }
        });

        btnEliminarDir.setText("Eliminar directorio");
        btnEliminarDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarDirActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnBorrarBak)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnMoverA)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminarDir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                        .addComponent(btnSalir)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBorrarBak)
                    .addComponent(btnMoverA)
                    .addComponent(btnSalir)
                    .addComponent(btnEliminarDir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBuscarActionPerformed
        activar(false);
        area.setText("");
        File buscar = new File(txtBuscar.getText());
        if(buscar.exists()){
                txtBuscar.setText(buscar.getPath());
                String aux = "";
                if (buscar.isFile()){
                    aux="Archivo";
                }
                else{
                    if (buscar.isDirectory()){
                        aux="Directorio";
                    }
                    else{
                        aux="Tipo Desconocido";
                    }
                }
                txtTipoArchivo.setText(aux);
                txtTamanio.setText(""+buscar.length());
                pintarArea(buscar);
        }
        else{
            if(txtBuscar.getText().compareTo("")!=0){
                JOptionPane.showMessageDialog(this, "No existe el directorio: "+txtBuscar.getText());
            }
            JFileChooser jf = new JFileChooser();
            jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int res = jf.showOpenDialog(this);
            if (res == JFileChooser.APPROVE_OPTION){
                File archi = jf.getSelectedFile();
                if (archi != null){
                    txtBuscar.setText(archi.getPath());
                    String aux = "";
                    if (archi.isFile()){
                        aux="Archivo";
                    }
                    else{
                        if (archi.isDirectory()){
                            aux="Directorio";
                        }
                        else{
                            aux="Tipo Desconocido";
                        }
                    }
                    txtTipoArchivo.setText(aux);
                    txtTamanio.setText(""+buscar.length());
                    pintarArea(archi);
                }
            }
        }
}//GEN-LAST:event_txtBuscarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        activar(false);
        area.setText("");
        JFileChooser jf = new JFileChooser();
        jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int res = jf.showOpenDialog(this);
        if (res == JFileChooser.APPROVE_OPTION){
            File archi = jf.getSelectedFile();
            if (archi != null){
                txtBuscar.setText(archi.getPath());
                String aux = "";
                if (archi.isFile()){
                    aux="Archivo";
                }
                else{
                    if (archi.isDirectory()){
                        aux="Directorio";
                    }
                    else{
                        aux="Tipo Desconocido";
                    }
                }
                txtTipoArchivo.setText(aux);
                txtTamanio.setText(""+archi.length());
                pintarArea(archi);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnBorrarBakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarBakActionPerformed
        FiltroBak filtro = new FiltroBak(".bak");
        File dir = new File(txtBuscar.getText());
        File file = null;
        String[] lista = dir.list(filtro);
        if(lista != null & lista.length > 0){
            String mensaje = "Archivos borrados:\n";
            for(int i = 0; i<lista.length;i++){
                    file = new File(txtBuscar.getText(),lista[i]);
                    String nomb = file.getName();
                    file.delete();
                    mensaje=mensaje+nomb+"\n";
            }
            JOptionPane.showMessageDialog(this,mensaje);
            pintarArea(dir);
        }
        else{
            JOptionPane.showMessageDialog(this,"El directorio \""+dir.getName()+"\" no contiene archivos .bak");
        }
}//GEN-LAST:event_btnBorrarBakActionPerformed

    private void btnMoverAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMoverAActionPerformed
        File dir = new File(txtBuscar.getText());
        File file = null;
        String[] lista = dir.list();
        if(lista != null & lista.length > 0){
            JFileChooser destino = new JFileChooser();
            destino.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int res = destino.showOpenDialog(this);
            if (res == JFileChooser.APPROVE_OPTION){
                String mensaje = "Archivos copiados:\n";
                Boolean seBorro = false;
                for(int i = 0; i<lista.length;i++){
                    file = new File(txtBuscar.getText(),lista[i]);
                    if (!file.isDirectory()){
                        String nomb = file.getName();
                        File nuevo = new File(destino.getSelectedFile(),nomb);
                        try {
                            nuevo.createNewFile();
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(this, "No se pudo copiar el archivo "+nomb);
                        }
                        mensaje=mensaje+nomb+"\n";
                        seBorro = true;
                        file.delete();
                    }
                }
                if(seBorro){
                    JOptionPane.showMessageDialog(this,mensaje);
                    pintarArea(dir);
                }
                else{
                    JOptionPane.showMessageDialog(this,"No se encontraron archivos en el directorio seleccionado");
                }
            }
        }
        else{
            JOptionPane.showMessageDialog(this,"El directorio \""+dir.getName()+"\" no contiene archivos");
        }
}//GEN-LAST:event_btnMoverAActionPerformed

    private void btnEliminarDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarDirActionPerformed
        File f = new File(txtBuscar.getText());
        eliminar(f);
        JOptionPane.showMessageDialog(this,"Directorio: "+txtBuscar.getText()+" borrado");
        limpiar();
    }//GEN-LAST:event_btnEliminarDirActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnSalirActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea area;
    private javax.swing.JButton btnBorrarBak;
    private javax.swing.JButton btnEliminarDir;
    private javax.swing.JButton btnMoverA;
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtBuscar;
    private javax.swing.JTextField txtTamanio;
    private javax.swing.JTextField txtTipoArchivo;
    // End of variables declaration//GEN-END:variables

    private void activar(Boolean elec){
        btnBorrarBak.setEnabled(elec);
        btnMoverA.setEnabled(elec);
        btnEliminarDir.setEnabled(elec);

    }

    private void limpiar(){
        txtBuscar.setText("");
        txtTipoArchivo.setText("");
        txtTamanio.setText("");
        area.setText("");
        btnBorrarBak.setEnabled(false);
        btnMoverA.setEnabled(false);
        btnEliminarDir.setEnabled(false);
    }

    private void pintarArea(File archi){
            area.setText("");
            if(archi.isDirectory()){
            activar(true);
            String [] archivos = archi.list();
            if (archivos != null){
                    for (int i=0; i<archivos.length; i++){
                    File arch = new File(archivos[i]);
                    area.append("Nombre: " + arch.getName() + "\tTamaño: " + arch.length() + "\n");
                }
            }
        }
    }

    private void eliminar(File dir){
        File file = null;
        String[] lista = dir.list();
        if(lista != null & lista.length > 0){
            for(int i = 0; i<lista.length;i++){
                file = new File(dir.getPath(),lista[i]);
                if(file.isDirectory()){
                    eliminar(file);
                }
                else{
                    file.delete();
                }
            }
        }
        dir.delete();
    }
}


